﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Zeus.Comunicaciones.Utilidades.Serializer
{
    public class JsonSerializer : ISerializer
    {
        public T Deserialize<T>(string data)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return default(T);
            }

            T obj;

            if (typeof(T).IsClass && typeof(T) != typeof(string))
            {
                obj = Activator.CreateInstance<T>();
            }
            else
            {
                obj = default(T);
            }

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            obj = (T)serializer.ReadObject(stream);
            stream.Close();
            return obj;
        }

        public string Serialize(object obj)
        {
            if (obj == null) { return null; }

            string json = JsonConvert.SerializeObject(obj);

            return json;
        }

        public string Serialize(Dictionary<string, object> dictionary)
        {
            if (dictionary == null) { return null; }

            string json = string.Empty;

            foreach (var element in dictionary)
            {
                json += ",\"" + element.Key + "\":" + Serialize(element.Value);
            }

            json = "{" + json.Substring(1) + "}";

            return json;
        }
    }
}
